﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using SvgViewer.Utilities;

namespace SvgViewer.Entities;

internal class FolderHandle
{
    public static readonly FolderHandle Instance = new();

    private FolderHandle() { }

    public ObservableCollection<FolderInfo> GetFolders()
    {
        var items = new ObservableCollection<FolderInfo> {
            new(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
                LanguageManager.Instance.GetText("MainView.Desktop"),
                FolderType.Desktop)
        };
        foreach (var dir in Directory.GetLogicalDrives())
        {
            items.Add(new FolderInfo(dir, dir, FolderType.Disk));
        }

        return items;
    }

    public void LoadChild(FolderInfo info)
    {
        info.Child.Clear();
        var dir = new DirectoryInfo(info.Path);
        foreach (var d in dir.GetDirectories())
        {
            if (VaildDirectory(d))
            {
                info.Child.Add(new FolderInfo(d.FullName, d.Name, FolderType.Folder));
            }
        }

        info.IsExpand = true;
    }

    public void SetFolderInitInfo(FolderInfo folder)
    {
        var dir = new DirectoryInfo(folder.Path);
        var has = false;
        try
        {
            foreach (var d in dir.GetDirectories())
            {
                if (VaildDirectory(d))
                {
                    has = true;
                    break;
                }
            }
        }
        catch
        {
            // ignored
        }

        if (has)
        {
            folder.Child = new ObservableCollection<FolderInfo> {
                new()
            };
        }
        else
        {
            folder.IsExpand = true;
        }
    }

    private bool VaildDirectory(DirectoryInfo dir)
    {
        if ((dir.Attributes & FileAttributes.NotContentIndexed) == FileAttributes.NotContentIndexed)
        {
            return false;
        }

        if ((dir.Attributes & FileAttributes.System) == FileAttributes.System)
        {
            if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
            {
                return false;
            }
        }

        return true;
    }
}